/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    InteractionManager
} from 'react-native';
import { SwipeListView,SwipeRow } from 'react-native-swipe-list-view';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import AddAnimals from './AddAnimals';
import shopService from '../lib/services/shopService';
import StorageUser from '../lib/plugins/StorageUser';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class PublicAnimals extends Component{
    constructor(props) {
        super(props);
        this.token = '';
        this.userId = '';
        this.shopId = '';
        this.rowList = [];
        var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource:ds.cloneWithRows(this.rowList),
        };
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }
                if(data.shopId){
                    $this.shopId = data.shopId;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getListData();
                });              
            }).catch(err=> {
                console.log(err)
            });
    }
    // 渲染列表每个活体
    renderListItem(rowData,sectionID,rowId){
        // alert(JSON.stringify(rowData))
        return(
            <View>
                <SwipeRow
                    closeOnRowPress={true}
                    rightOpenValue={-120} 
                    disableRightSwipe={true}>
                    <View style={{flex:1,flexDirection:'row',justifyContent:'flex-end'}}>
                        <TouchableOpacity style={{backgroundColor:'#ccc',width:60,alignItems:'center',justifyContent:'center'}} onPress={()=>this.goEditAnimals(rowData)}>
                            <View>
                                <Text style={{color:'#fff',fontSize:16}}>编辑</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={()=>this.deleteAnimal(rowData,rowId)} style={{backgroundColor:'#ff0000',width:60,alignItems:'center',justifyContent:'center'}}>
                            <View>
                                <Text style={{color:'#fff',fontSize:16}}>删除</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View>
                        <GoodsDetail 
                            name={rowData.merchant_name} 
                            icon={{uri:'http://peita.oss-cn-beijing.aliyuncs.com/'+rowData.sl_img}} 
                            imgWidth={80} imgHeight={80} 
                            goodsNum={rowData.num}
                            brand={rowData.cate}
                            price={rowData.price}/>
                    </View>
                </SwipeRow>
            </View>
        )
    }
    

    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'活体宠物'} 
                    leftPress={()=>this.goBack()}
                    rightText={'+'}
                    rightTextPress={()=>this.goAddAnimals()}
                    rightTextStyle={{color:'#fff',fontSize:24}}/>
                <ScrollView>
                    <View style={styles.navBox}>
                        <TouchableOpacity onPress={()=>this.sortList(1)} style={styles.borderBox}>
                            <View style={styles.textBox}>
                                <Text>月龄</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={()=>this.sortList(2)} style={styles.borderBox}>
                            <View style={styles.textBox}>
                                <Text>品种</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <SwipeListView
                        dataSource={this.state.dataSource}
                        closeOnRowPress={true}
                        enableEmptySections={true}
                        closeOnRowBeginSwipe={true}
                        renderRow={(rowData,sectionID,rowId) => this.renderListItem(rowData,sectionID,rowId)}/>
                </ScrollView>
            </View>
        )

    }

    goBack(){
        this.props.navigation.goBack();
    }
    // 调用接口获取发布的活体列表数据
    getListData(){
        var $this = this;
        shopService.myLivingLists(function(data){
            // alert(JSON.stringify(data));
            if(data.code==10000){
                $this.rowList = data.data;
                $this.setState({
                    dataSource:$this.state.dataSource.cloneWithRows($this.rowList)
                })
            }
        },$this.userId,$this.shopId,$this.token);
    }
    goAddAnimals(){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('AddAnimals',{staturs:'添加活体',backUpData:()=>{
            $this.getListData();
        }})
    }
    goEditAnimals(rowData){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('AddAnimals',{staturs:'编辑活体',id:rowData.sl_id,backUpData:()=>{
            $this.getListData();
        }})
    }

    deleteAnimal(rowData,rowId){
        var $this = this;
        shopService.myReleaseLivingIdDel(function(data){
            // alert(JSON.stringify(data))
            if(data.code==10000){
                $this.rowList.splice(rowId,1);
                $this.rowList = JSON.parse(JSON.stringify($this.rowList))
                $this.setState({
                    dataSource:$this.state.dataSource.cloneWithRows($this.rowList)
                })
            }
        },rowData.sl_id,$this.token)
    }
    // 列表排序
    sortList(type){
        var $this = this;
        shopService.myReleaseLivingListsSort(function(data){
            if(data.code==10000){
                $this.rowList = data.data;
                $this.setState({
                    dataSource:$this.state.dataSource.cloneWithRows($this.rowList)
                })
            }
        },$this.userId,type,$this.token);
    }

}

class GoodsDetail extends Component{
    render(){
        var imgWidth = this.props.imgWidth;
        var imgHeight = this.props.imgHeight;
        return(
            <View style={styles.itemContainer}>
                <View>
                    <Image style={{width:imgWidth,height:imgHeight}} source={this.props.icon}/>
                </View>
                <View style={{marginLeft:10,flex:1}}>
                    <View style={[styles.itemLine,{flex:1}]}>
                        <Text style={styles.itemTitle}>{this.props.name}</Text>
                    </View>
                    <View style={{flexDirection:'row',flex:1}}>
                        <View style={[styles.itemLine,{flex:1}]}>
                            <Text style={{fontSize:10}}>库存 : {this.props.goodsNum}</Text>
                        </View>
                        <View style={[styles.itemLine,{flex:1}]}>
                            <Text style={{fontSize:10}}>品种 : {this.props.brand}</Text>
                        </View>
                    </View>
                    <View style={{flex:1}}>
                        <Text style={{color:'#F8530B',fontSize:16}}>￥{this.props.price}</Text>
                    </View>
                </View>
            </View>
        )
    }

}



const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    }, 
    itemContainer:{
        flexDirection:'row',
        alignItems:'center',
        padding:5,
        backgroundColor:'#fff',
        borderBottomWidth:1,
        borderBottomColor:'#ccc'
    },
    modalBox:{
        flex:1,
        backgroundColor:'rgba(3,3,3,.2)',
        justifyContent:'center',
        alignItems:'center',
    },
    listItem:{
        width:3*width/4,
        height:40,
        justifyContent:'center',
        backgroundColor:'#fff',
        paddingLeft:10,
    },
    navBox:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center',
        height:30,
        backgroundColor:'#fff',
        
    },
    textBox:{
        justifyContent:'center',
        alignItems:'center',

    },
    borderBox:{
        borderWidth:1,
        borderColor:'#ccc',
        borderRadius:3,
        height:30,
        flex:1,
        justifyContent:'center'
    }
    
});